package io.github.uicdb.badskill.clent;

import lombok.Getter;
import lombok.Setter;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.narration.NarrationElementOutput;
import net.minecraft.network.chat.Component;
import net.minecraft.util.FormattedCharSequence;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.function.Supplier;

public class TextView extends AbstractWidget {
    private final Supplier<List<? extends Component>> textGetter;

    @Setter
    protected int color;
    private final Font font;
    @Getter
    protected float textScale =1f;
    public TextView(int pX, int pY, int pWidth, int pHeight, Supplier<List<? extends Component>> textGetter) {
        super(pX, pY, pWidth, pHeight, Component.literal("textview"));
        this.textGetter=textGetter;
        this.font=Minecraft.getInstance().font;
    }
    protected float getTextHeight(){
        return textGetter.get().stream().map(component -> (font.wordWrapHeight(component,getRealWidth())*textScale)).reduce(0f,Float::sum);
    }
    protected int getRealWidth(){
        return (int) (width/ textScale);
    }

    public void setTextScale(float scale) {
        this.textScale = Math.max(scale,0.1f);
    }
    protected float getStartY(){
        return getY()-getTextHeight()/2+getHeight()/2;
    }
    @Override
    public void renderWidget(@NotNull GuiGraphics pPoseStack, int pMouseX, int pMouseY, float pPartialTick) {
        List<? extends Component> text=textGetter.get();
        var w=getRealWidth();
        float nextY=getStartY();

        for (Component component : text) {
            for(FormattedCharSequence formattedcharsequence : font.split(component, w)) {
                pPoseStack.pose().pushPose();
                pPoseStack.pose().translate(getX(),nextY,0);
                pPoseStack.pose().scale(textScale, textScale, textScale);
                pPoseStack.drawString(font, formattedcharsequence, 0, 0, color, false);
                nextY += 9*textScale;
                pPoseStack.pose().popPose();
            }

        }

    }


    @Override
    protected void updateWidgetNarration(@NotNull NarrationElementOutput p_259858_) {

    }
}
